package com.cssiot.weixin.basic.util;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.security.KeyManagementException;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;

import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocket;
import javax.net.ssl.TrustManagerFactory;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.protocol.HttpClientContext;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.ssl.SSLContextBuilder;
import org.apache.http.ssl.TrustStrategy;
import org.apache.http.util.EntityUtils;  
  
public class Http   
{  
	
	private static CloseableHttpClient client = HttpClients.createDefault();
    public static SSLContext getSSLContext() throws Exception  
    {  
        KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());  
//        InputStream input = new FileInputStream("D:/apache-tomcat-8.0.26-testHttps/oneWay/truststore.jks");  
        InputStream input = new FileInputStream("D:/apache-tomcat-8.0.26-testHttps/doubleWay/tomcat.jks");  
        ks.load(input, "123456".toCharArray());  
          
        TrustManagerFactory tmf = TrustManagerFactory.getInstance("SunX509");  
        tmf.init(ks);  
          
        SSLContext context = SSLContext.getInstance("TLSv1.2");  
        //这里只指定了受信任的证书（单向认证），如果是双向认证的话，则第一个参数不能为null  
        context.init(null, tmf.getTrustManagers(), null);  
        return context;  
    } 
    
    /**
     * 双向验证
     * @return
     * @throws Exception
     */
    public static SSLContext getSSLContext2() throws Exception  
    {  
//        KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());  
//        InputStream input = new FileInputStream("D:/apache-tomcat-8.0.26-testHttps/oneWay/truststore.jks");  
//        InputStream input = new FileInputStream("D:/apache-tomcat-8.0.26-testHttps/doubleWay/tomcat.jks");  

        KeyStore ks = KeyStore.getInstance("JKS");  
        KeyStore tks = KeyStore.getInstance("JKS");  
        KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");  
        TrustManagerFactory tmf = TrustManagerFactory.getInstance("SunX509");  
         
         ks.load(new FileInputStream("D:/apache-tomcat-8.0.26-testHttps/doubleWay/tomcat.jks"), "123456".toCharArray());  
         tks.load(new FileInputStream("D:/apache-tomcat-8.0.26-testHttps/oneWay/truststore.jks"), "123456".toCharArray());  

         kmf.init(ks, "123456".toCharArray());  
         tmf.init(tks);  

         SSLContext context = SSLContext.getInstance("TLSv1.2");  
        //这里只指定了受信任的证书（单向认证），如果是双向认证的话，则第一个参数不能为null  
         context.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null);  
        return context;  
    } 
    public static void main(String[] args) throws Exception  
    {  
        
    /*   HttpClientBuilder builder = HttpClients.custom();  
        builder.setSSLContext(getSSLContext());  
       CloseableHttpClient httpclient = builder.build();  
        HttpGet httpget = new HttpGet("https://localhost:8443/wx/hello/rest/123");  
        CloseableHttpResponse response = httpclient.execute(httpget);  
        int statusCode = response.getStatusLine().getStatusCode();
		if(statusCode>=200&&statusCode<300) {
			System.out.println("restGet请求返回成功");
		}
        HttpEntity entity = response.getEntity();  
        String body = EntityUtils.toString(entity);  
        System.out.println(body);  
        response.close();  
        httpclient.close(); */
    	
//    	oneWayAuthorizationAccepted();
        
        doubleWay();
        
        
        
//    	跳过证书
//      CloseableHttpClient httpClient =  createSSLClientDefault();
  /*      HttpGet get = new HttpGet("https://localhost:8443/wx/hello/rest/123");
//        get.setURI(new URI("https://localhost:8443/wx/hello/rest/123"));
        CloseableHttpResponse response = httpClient.execute(get);
        int statusCode = response.getStatusLine().getStatusCode();
		if(statusCode>=200&&statusCode<300) {
			System.out.println("restGet请求返回成功");
		}*/
    }  
    
	public static CloseableHttpClient createSSLClientDefault() {
		try {
			SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {
				// 信任所有
				public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException {
					return true;
				}
			}).build();
			SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext);
			return HttpClients.custom().setSSLSocketFactory(sslsf).build();
		} catch (KeyManagementException e) {
			e.printStackTrace();
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		} catch (KeyStoreException e) {
			e.printStackTrace();
		}
		return HttpClients.createDefault();
	}
	
	  /**
     * 单向验证且服务端的证书可信
     * @throws IOException 
     * @throws ClientProtocolException 
     */
    public static void oneWayAuthorizationAccepted() throws Exception {
        // Execution context can be customized locally.
        HttpClientContext context = HttpClientContext.create();
        HttpGet httpget = new HttpGet("https://localhost:8443/wx/hello/rest/99");
        // 设置请求的配置
        RequestConfig requestConfig = RequestConfig.custom()
                .setSocketTimeout(5000).setConnectTimeout(5000)
                .setConnectionRequestTimeout(5000).build();
        httpget.setConfig(requestConfig);

        System.out.println("executing request " + httpget.getURI());
        CloseableHttpResponse response =  client.execute(httpget, context);
        int statusCode = response.getStatusLine().getStatusCode();
		if(statusCode>=200&&statusCode<300) {
			System.out.println("restGet请求返回成功");
		}
        try {
            System.out.println("----------------------------------------");
            System.out.println(response.getStatusLine());
            System.out.println(EntityUtils.toString(response.getEntity()));
            System.out.println("----------------------------------------");

            // Once the request has been executed the local context can
            // be used to examine updated state and various objects affected
            // by the request execution.

            // Last executed request
            context.getRequest();
            // Execution route
            context.getHttpRoute();
            // Target auth state
            context.getTargetAuthState();
            // Proxy auth state
            context.getTargetAuthState();
            // Cookie origin
            context.getCookieOrigin();
            // Cookie spec used
            context.getCookieSpec();
            // User security token
            context.getUserToken();

        } catch (Exception e) {
            e.printStackTrace();
        }

    }
    
    
    public static void doubleWayAuthorizationAccepted() throws  Exception {
        // Execution context can be customized locally.
        HttpClientContext context = HttpClientContext.create();
        HttpGet httpget = new HttpGet("https://localhost:8443/wx/hello/rest/99");
        // 设置请求的配置
        RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(5000).setConnectTimeout(5000)
                .setConnectionRequestTimeout(5000).build();
        httpget.setConfig(requestConfig);

        System.out.println("executing request " + httpget.getURI());
        CloseableHttpResponse response =client.execute(httpget, context);
        try {
            System.out.println("----------------------------------------");
            System.out.println(response.getStatusLine());
            System.out.println(EntityUtils.toString(response.getEntity()));
            System.out.println("----------------------------------------");

            // Once the request has been executed the local context can
            // be used to examine updated state and various objects affected
            // by the request execution.

            // Last executed request
            context.getRequest();
            // Execution route
            context.getHttpRoute();
            // Target auth state
            context.getTargetAuthState();
            // Proxy auth state
            context.getTargetAuthState();
            // Cookie origin
            context.getCookieOrigin();
            // Cookie spec used
            context.getCookieSpec();
            // User security token
            context.getUserToken();

        } catch (Exception e) {
            e.printStackTrace();
        }

    }
    /**
     * 双向验证
     * @throws Exception
     */
    public static void doubleWay() throws  Exception{
    	 
    	  HttpClientBuilder builder = HttpClients.custom();  
          builder.setSSLContext(getSSLContext2());  
            
          CloseableHttpClient httpclient = builder.build();  
          HttpGet httpget = new HttpGet("https://localhost:8443/wx/hello/rest/123");  
          CloseableHttpResponse response = httpclient.execute(httpget);  
          int statusCode = response.getStatusLine().getStatusCode();
  		if(statusCode>=200&&statusCode<300) {
  			System.out.println("restGet请求返回成功");
  		}
          HttpEntity entity = response.getEntity();  
          String body = EntityUtils.toString(entity);  
          System.out.println(body);  
          response.close();  
          httpclient.close();  
      	
    }
  
	 
}  